package com.lxs.mall.ware.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.lxs.common.constant.WareConstant;
import com.lxs.mall.ware.entity.PurchaseDetailEntity;
import com.lxs.mall.ware.service.PurchaseDetailService;
import com.lxs.mall.ware.service.WareSkuService;
import com.lxs.mall.ware.vo.MergeVO;
import com.lxs.mall.ware.vo.PurchaseDoneVO;
import com.lxs.mall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxs.common.utils.PageUtils;
import com.lxs.common.utils.Query;

import com.lxs.mall.ware.dao.PurchaseDao;
import com.lxs.mall.ware.entity.PurchaseEntity;
import com.lxs.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 查询采购单的状态为 新建 或者 已分配 的采购单信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        // 添加查询的条件
        queryWrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 完成采购需求的合并操作
     * @param mergeVO
     */
    @Override
    public Integer merge(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        if(purchaseId==null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setCreateTime(new Date());
            this.save(purchaseEntity);
            purchaseId=purchaseEntity.getId();
        }
        //判断采购单的状态，只能是新建的，已分配的才能合并，已分配的就不能再合并了
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if(purchaseEntity.getStatus()>WareConstant.PurchaseStatusEnum.ASSIGED.getCode()){
            return -1;
        }
        //增和菜单需求单
        final Long finalPurchaseId= purchaseId;
        List<Long> items = mergeVO.getItems();
        List<PurchaseDetailEntity> detailEntities = items.stream().map(i -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setPurchaseId(finalPurchaseId);
            ;
            detailEntity.setId(i);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            return detailEntity;
        }).filter(i -> {
            PurchaseDetailEntity detailEntity = purchaseDetailService.getById(i);
            if (detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode()
                    || detailEntity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(detailEntities)){
            purchaseDetailService.updateBatchById(detailEntities);
        }
        //更新对应的采购单的更新时间
        PurchaseEntity entity = new PurchaseEntity();
        entity.setUpdateTime(new Date());
        entity.setId(purchaseId);
        this.updateById(entity);
        return 1;
    }

    /**
     * 领取采购单，只能是新建、已分配的状态，其他状态是不能领取的
     * @param ids
     */
    @Transactional
    @Override
    public void receive(List<Long> ids) {
        //1,领取的采购单的状态只能是新建或已分配的状态，其他状态是不能领取的
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(purchaseEntity -> {
            if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {
                return true;
            }
            return false;
        }).map(purchaseEntity -> {
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());
        //2,更新采购单的状态为已领取
        this.updateBatchById(purchaseEntities);
        //3,更新采购项为正在采购中
        for(Long id:ids){
            QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("purchase_id",id);
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.list(wrapper);
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(e -> {
                e.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return e;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }
    }
    @Transactional
    @Override
    public void done(PurchaseDoneVO vo) {
        //1，获得采购项编号
        Long id= vo.getId();
        //2，更新采购项状态
        Boolean flag = true; // 记录采购的状态 默认为 完成
        List<PurchaseItemDoneVO> items = vo.getItems();
        List<PurchaseDetailEntity> detailEntityArrayList = new ArrayList<PurchaseDetailEntity>();
        for(PurchaseItemDoneVO item :items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                //该采购项出现了问题
                flag=false;
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else{
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //根据采购项编号查询出采购项详情
                PurchaseDetailEntity detailEntity1 = purchaseDetailService.getById(item.getItemId());
                //3,采购项成功的进入库操作
                wareSkuService.updateStock(detailEntity1.getSkuId(),detailEntity1.getWareId(),detailEntity1.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            detailEntityArrayList.add(detailEntity);
        }
        //批量更新订单项
        purchaseDetailService.updateBatchById(detailEntityArrayList);
        //4,更新采购单
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():
                WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(id);
        this.updateById(purchaseEntity);

    }

}
